package com.qf.shiro;

import com.qf.pojo.DtsAdmin;
import com.qf.pojo.DtsPermission;
import com.qf.pojo.DtsRole;
import com.qf.service.AdminService;
import com.qf.service.DtsPermissonService;
import com.qf.service.DtsRolesService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class AdminAuthorizingRealm extends AuthorizingRealm  {
    @Autowired
    AdminService adminService;
    @Autowired
    DtsRolesService rolesService;
    @Autowired
    DtsPermissonService permissonService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
      DtsAdmin admin= (DtsAdmin) getAvailablePrincipal(principalCollection);
        Integer[] roleIds = admin.getRoleIds();
        //查询角色集合
        Set<String>roles= rolesService.findByRoleIds(roleIds);
        //查询权限集合
        Set<String> permissions=permissonService.findByRoleIds(roleIds);
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permissions);

        return authorizationInfo;
    }



    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String  username =(String) authenticationToken.getPrincipal();
        String password =new String ((char[])authenticationToken.getCredentials());
        //获取数据库中的用户名和密码
        //根据用户名获取管理员信息
        DtsAdmin admin=adminService.findByUsernma(username);
        if(admin==null){
            throw new UnknownAccountException("用户名不存在");
        }
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();


        if(!encoder.matches(password,admin.getPassword())||password==null){
            throw new CredentialsException("密码错误");
        }
        if(admin.getDeleted()){
            throw new LockedAccountException("账户已锁定");
        }
        AuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(admin,password,admin.getUsername());

           return authenticationInfo;
    }
}
